<template>
  <div v-if="$attrs.stationAttr">
    <TableSearch
      ref="tableSearch"
      :columns="columns"
      :tableData="tableData"
      :tableBtns="tableBtns"
      :form="form"
      :formItemsInline="formItemsInline"
      :search-path="searchPath"
      :span-method="objectSpanMethod"
      @handleTableData="handleTableData"
      @reset="reset"
      @multipleSelection="multipleSelection"
      :header-cell-style="hideHeader"
    >
      <el-table-column label="按钮" slot="button" width="120px">
        <template #default="{ row }">
          <el-button
            v-if="
              resourceSet.includes(
                '/web/device-management/station-management/detail/自检'
              ) && row.type !== 'CENTRAL_SOCKET'
            "
            class="table-button-green"
            @click="handleSelfCheck(row)"
            >自检</el-button
          >
          <!-- <el-button
            v-if="
              resourceSet.includes(
                '/web/device-management/station-management/detail/导出二维码'
              )
            "
            class="table-button-green"
            @click="handleExport(row)"
            >导出二维码</el-button
          > -->
        </template>
      </el-table-column>
    </TableSearch>
    <AddDevice
      v-if="addDeviceVisible"
      @refreshTable="refreshTable"
      :visible.sync="addDeviceVisible"
      :station-attr="stationAttr"
      :partner-options="partnerOptions"
    />
    <BatchUpload
      v-if="batchUploadVisible"
      :visible.sync="batchUploadVisible"
      @refreshTable="refreshTable"
      :dialog-type="dialogType"
      :station-attr="stationAttr"
    ></BatchUpload>
    <MigrateDevice
      v-if="migrateDeviceVisible"
      :visible.sync="migrateDeviceVisible"
      @refreshTable="refreshTable"
      :device-attr="deviceAttr"
    ></MigrateDevice>
    <CoupletCard
      v-if="coupletCardVisible"
      :visible.sync="coupletCardVisible"
      :couplet-card="coupletCard"
    ></CoupletCard>
    <EditLabel
      v-if="editLabelVisible"
      :visible.sync="editLabelVisible"
      @refreshTable="refreshTable"
      :device-attr="deviceAttr"
    ></EditLabel>
    <PortsListForCentralSocket
      :visible.sync="viewPortsListVisible"
      :portsList="portsList"
    >
    </PortsListForCentralSocket>
  </div>
</template>
<script>
import TableSearch from '@/components/TableSearch'
import {
  stationDetailList,
  cancelDevice,
  detailSelfCheck,
  coupletCardStatus,
  detailResetDevice,
  enableDevice,
} from '@/api/device'
import { partnerList } from '@/api/user'
import AddDevice from './AddDevice'
import BatchUpload from './BatchUpload'
import MigrateDevice from './MigrateDevice'
import CoupletCard from './CoupletCard'
import EditLabel from './EditLabel'
import { genQrcode } from '@/utils'
import { typeMap } from '@/utils/format'
import formatter from '@/utils/format'
import PortsListForCentralSocket from './PortsListForCentralSocket'
export default {
  name: 'DetailGatewayTable',
  components: {
    TableSearch,
    AddDevice,
    BatchUpload,
    MigrateDevice,
    CoupletCard,
    EditLabel,
    PortsListForCentralSocket,
  },
  data() {
    return {
      addDeviceVisible: false,
      stationAttr: {},
      deviceAttr: {},
      coupletCard: {},
      portsList: {},
      batchUploadVisible: false,
      viewPortsListVisible: false,
      migrateDeviceVisible: false,
      coupletCardVisible: false,
      editLabelVisible: false,
      dialogType: 'ADD',
      form: {
        deviceStatus: 'ALL',
      },
      tableData: {},
      area: {},
      deviceIds: [],
      partnerOptions: [],
      searchPath: '/web/device-management/station-management/detail/查询',
      tableBtns: [
        {
          label: '添加',
          click: this.handleAdd,
          icon: 'el-icon-plus',
          resourceId: '/web/device-management/station-management/detail/添加',
          // ifRender: () => {
          //   return this.$attrs.stationAttr.stationUserId === this.userId
          // },
        },
        {
          label: '注销所选项',
          click: () => this.handleLogout('batch'),
          icon: 'el-icon-delete',
          type: 'warning',
          resourceId:
            '/web/device-management/station-management/detail/注销所选项',
          // ifRender: () => {
          //   return this.$attrs.stationAttr.stationUserId === this.userId
          // },
        },
        {
          label: 'Excel批量添加',
          click: () => this.handleBatchUpload('ADD'),
          icon: 'el-icon-plus',
          resourceId:
            '/web/device-management/station-management/detail/EXCEL批量添加',
          // ifRender: () => {
          //   return this.$attrs.stationAttr.stationUserId === this.userId
          // },
        },
        {
          label: '(批量激活模板下载)',
          isDownload: true,
          href: require('../../../assets/batchTemplate/批量激活设备模板.xlsx'),
          fileName: '批量激活设备模板',
          resourceId:
            '/web/device-management/station-management/detail/EXCEL批量添加',
          ifRender: () => {
            return this.$attrs.type !== 'CENTRAL_SOCKET'
          },
        },
        {
          label: '(批量激活模板下载)',
          isDownload: true,
          href: require('../../../assets/batchTemplate/批量激活集中式设备模板.xlsx'),
          fileName: '批量激活设备模板',
          resourceId:
            '/web/device-management/station-management/detail/EXCEL批量添加',
          ifRender: () => {
            return this.$attrs.type === 'CENTRAL_SOCKET'
          },
        },
        {
          label: 'Excel批量注销',
          click: () => this.handleBatchUpload('LOGOUT'),
          icon: 'el-icon-delete',
          type: 'warning',
          resourceId:
            '/web/device-management/station-management/detail/EXCEL批量注销',
          // ifRender: () => {
          //   return this.$attrs.stationAttr.stationUserId === this.userId
          // },
        },
        {
          label: '(批量注销模板下载)',
          isDownload: true,
          href: require('../../../assets/batchTemplate/批量注销设备模板.xlsx'),
          fileName: '批量注销设备模板',
        },
        {
          label: '设备二维码批量导出',
          click: () => this.handleExport(),
          icon: 'el-icon-tickets',
          resourceId:
            '/web/device-management/station-management/detail/设备二维码批量导出',
          ifRender: () => {
            return this.$attrs.type !== 'GATEWAY'
          },
        },
      ],
      formItemsInline: [
        {
          type: 'text',
          value: 'deviceId',
          placeholder: '请输入设备号',
          clearable: true,
          resourceId: '/web/device-management/station-management/detail/设备号',
        },
        {
          type: 'text',
          value: 'coupletCard',
          placeholder: '请输入物联卡号',
          clearable: true,
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
          resourceId:
            '/web/device-management/station-management/detail/物联卡号',
        },
        {
          type: 'radio',
          value: 'deviceStatus',
          options:
            this.$attrs.type === 'GATEWAY' ||
            this.$attrs.type === 'CENTRAL_SOCKET'
              ? typeMap.radioOptions(
                  ['BREAK_DOWN', 'CHARGING', 'IDLE'],
                  'deviceStatus'
                )
              : typeMap.radioOptions(['ONLINE'], 'deviceStatus'),
          resourceId: '/web/device-management/station-management/detail/状态',
        },
      ],
      columns: [
        {
          type: 'selection',
          resourceId: '/web/device-management/station-management/detail/全选',
        },
        {
          label: '设备号',
          // prop:
          //   this.$attrs.type === 'GATEWAY' ||
          //   this.$attrs.type === 'CENTRAL_SOCKET' ||
          //   this.$attrs.type === 'ZT_SOCKET'
          //     ? 'deviceId'
          //     : 'socketId',
          prop: 'deviceId',
          resourceId: '/web/device-management/station-management/detail/设备号',
        },
        {
          label: '端口号',
          prop: 'socketId',
          resourceId: '/web/device-management/station-management/detail/设备号',
        },
        {
          label: '设备类型',
          prop: 'type',
          resourceId:
            '/web/device-management/station-management/detail/设备类型',
          formatter: (row) => {
            return row.type.description
          },
        },
        {
          label: '注册状态',
          prop: 'activeDate',
          resourceId: '/web/device-management/device-management/设备号',
          formatter: (row) => {
            return row.activeDate ? '已注册' : '未注册'
          },
        },
        // {
        //   label: '添加时间',
        //   prop: 'activeDate',
        //   resourceId:
        //     '/web/device-management/station-management/detail/添加时间',
        //   formatter,
        // },
        {
          label: '物联卡号',
          prop: 'coupletCard',
          resourceId:
            '/web/device-management/station-management/detail/物联卡号',
          hidden: () => {
            return this.$attrs.type !== 'GATEWAY'
          },
        },
        {
          label: '厂商',
          prop: 'mchName',
          resourceId: '/web/device-management/station-management/detail/厂商',
          hidden: () => {
            return this.$attrs.type !== 'CENTRAL_SOCKET'
          },
        },
        {
          label: '端口数',
          prop: 'socketsNum',
          resourceId: '/web/device-management/station-management/detail/端口数',
          hidden: () => {
            return this.$attrs.type !== 'CENTRAL_SOCKET'
          },
        },
        {
          label: '状态',
          prop: 'online',
          resourceId: '/web/device-management/station-management/detail/状态',
          formatter:
            this.$attrs.type === 'GATEWAY' ||
            this.$attrs.type === 'CENTRAL_SOCKET' ||
            this.$attrs.type === 'ZT_SOCKET'
              ? (row) => {
                  return row.online ? '在线' : '失联'
                }
              : (row) => {
                  return typeMap.deviceStatus[row.socketStatus]
                },
        },
        {
          label: '停用状态',
          prop: 'enableStatus',
          resourceId:
            '/web/device-management/station-management/detail/停用状态',
          hidden: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET' ||
              this.$attrs.type === 'ZT_SOCKET'
            )
          },
          formatter: (row) => {
            return row.enableStatus ? '正常' : '停用'
          },
        },
        {
          label: '标签',
          prop: 'label',
          resourceId: '/web/device-management/station-management/detail/标签',
        },
        {
          label: '操作',
          resourceId: '/web/device-management/station-management/detail/操作',
          buttons: [
            {
              label: '导出二维码',
              resourceId:
                '/web/device-management/station-management/detail/导出二维码',
              click: (row) => {
                this.handleExport(row)
              },
            },
            {
              label: '注销',
              resourceId:
                '/web/device-management/station-management/detail/注销',
              click: (row) => {
                this.handleLogout('single', row)
              },
              // disabled: () => {
              //   return this.$attrs.stationAttr.stationUserId !== this.userId
              // },
            },
            {
              label: '复位',
              resourceId:
                '/web/device-management/station-management/detail/复位',
              click: this.handleResetDevice,
            },
            {
              label: '端口详情',
              resourceId: '/web/device-management/device-management/端口详情',
              ifRender: () => {
                return this.$attrs.type === 'CENTRAL_SOCKET'
              },
              click: (row) => {
                this.viewPortsListVisible = true
                this.portsList = row
              },
            },
            {
              label: '停用',
              resourceId:
                '/web/device-management/station-management/detail/停用',
              click: this.handleStatus,
              ifRender: (row) => {
                return row.enableStatus
              },
            },
            {
              label: '启用',
              resourceId:
                '/web/device-management/station-management/detail/停用',
              click: this.handleStatus,
              ifRender: (row) => {
                return !row.enableStatus
              },
            },
            {
              label: '迁移',
              resourceId:
                '/web/device-management/station-management/detail/迁移',
              click: this.handleMigrate,
              // disabled: () => {
              //   return this.$attrs.stationAttr.stationUserId !== this.userId
              // },
            },
            {
              label: '查询卡状态',
              resourceId:
                '/web/device-management/station-management/detail/查询卡状态',
              ifRender: () => {
                return this.$attrs.type === ('GATEWAY' || 'NB_DEVICE')
              },
              click: this.handleCoupletCardStatus,
            },
            {
              label: '编辑标签',
              resourceId:
                '/web/device-management/station-management/detail/编辑标签',
              click: this.handleLabel,
            },
          ],
        },
        // {
        //   slot: 'button',
        //   resourceId: '/web/device-management/station-management/detail/操作',
        //   hidden: () => {
        //     return (
        //       this.$attrs.type === 'GATEWAY' ||
        //       this.$attrs.type === 'ZT_SOCKET' ||
        //       (!this.resourceSet.includes(
        //         '/web/device-management/station-management/detail/自检'
        //       ) &&
        //         !this.resourceSet.includes(
        //           '/web/device-management/station-management/detail/导出二维码'
        //         ))
        //     )
        //   },
        // },
      ],
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
    // userId() {
    //   return this.$store.getters.userId
    // },
    test() {
      return this.$attrs.stationAttr
    },
  },
  methods: {
    objectSpanMethod({ row, column }) {
      if (
        this.$attrs.type === 'GATEWAY' ||
        this.$attrs.type === 'CENTRAL_SOCKET'
      ) {
        return
      }
      if (
        column.label !== '状态' &&
        column.label !== '按钮' &&
        column.label !== '端口号'
      ) {
        return {
          rowspan: row.socketLength,
          colspan: 1,
        }
      }
    },
    hideHeader({ column }) {
      console.log(this.$attrs.type)
      if (
        this.$attrs.type === 'GATEWAY' ||
        this.$attrs.type === 'CENTRAL_SOCKET' ||
        this.$attrs.type === 'ZT_SOCKET'
      ) {
        return
      }
      if (column.label === '按钮') {
        return { display: 'none' }
      } else if (column.label == '操作') {
        this.$nextTick(() => {
          let nextSibling = document.getElementsByClassName(column.id)[0]
            .nextSibling
          if (
            nextSibling &&
            nextSibling.childNodes[0] &&
            nextSibling.childNodes[0].innerHTML === '按钮'
          ) {
            document
              .getElementsByClassName(column.id)[0]
              .setAttribute('colspan', 2)
          }
        })
      }
    },
    reset() {
      this.form = {
        deviceStatus: 'ALL',
      }
      this.area = {}
    },
    handleSocket(arr) {
      let list = []
      arr.forEach((item) => {
        let sockets = item.sockets
        if (item.type === 'CENTRAL_SOCKET') {
          sockets.forEach((socket, index) => {
            list.push({
              socketId: socket.socketId,
              socketStatus: socket.socketStatus,
              socketLength: index === 0 ? sockets.length : 0,
              ...item,
            })
          })
        } else {
          sockets.forEach((socket, index) => {
            list.push({
              socketId: socket.socketId,
              socketStatus: socket.socketStatus,
              socketLength: index === 0 ? sockets.length : 0,
              ...item,
            })
          })
        }
      })
      return list
    },
    handleTableData(params) {
      if (params.deviceStatus === 'ALL') {
        delete params.deviceStatus
      }
      params = {
        ...params,
        deviceType: this.$attrs.type,
        stationId: this.$route.params.id,
      }
      stationDetailList(params).then((res) => {
        this.tableData = {
          list:
            this.$attrs.type === 'GATEWAY' ||
            this.$attrs.type === 'CENTRAL_SOCKET'
              ? res.list
              : this.handleSocket(res.list),
          totalCount: res.totalAmount,
        }
        console.log(this.tableData)
      })

      this.handleGetPartner()
    },
    multipleSelection(val) {
      let deviceIds = []
      val.forEach((item) => {
        deviceIds.push(item.deviceId)
      })
      this.deviceIds = deviceIds
    },
    handleResetDevice(row) {
      this.$confirm(`您确定要复位设备号为${row.deviceId}的设备吗？`, '提示', {
        center: true,
        customClass: 'tip-dialog__wrapper',
      })
        .then(() => {
          detailResetDevice({
            deviceId: row.deviceId,
          }).then(() => {
            this.$message({
              message: '复位成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },
    handleStatus(row) {
      this.$confirm(
        `您确定要${row.enableStatus ? '停用' : '启用'}设备号为${
          row.deviceId
        }的设备吗？`,
        '提示',
        {
          center: true,
          customClass: 'tip-dialog__wrapper',
        }
      )
        .then(() => {
          enableDevice({
            deviceId: row.deviceId,
            enableStatus: row.enableStatus ? 0 : 1,
          }).then(() => {
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
      enableDevice({ deviceId: row.deviceId, enableStatus: row.enableStatus })
    },
    handleLogout(type, data) {
      if (type === 'batch' && !this.deviceIds.length) {
        this.$message({
          showClose: true,
          message: '请先勾选要注销的设备！',
        })
        return
      }
      this.$confirm(
        type === 'batch'
          ? '您确定要批量注销选中的设备吗?'
          : `您确定要注销设备编号为${data.deviceId}的设备吗？`,
        '提示',
        {
          center: true,
          customClass: 'tip-dialog__wrapper',
        }
      )
        .then(() => {
          cancelDevice({
            deviceIds: type === 'batch' ? this.deviceIds : [data.deviceId],
          }).then((res) => {
            if (res.successNum === res.total) {
              this.$message({
                message: '注销成功',
                type: 'success',
              })
            } else {
              this.$message({
                message:
                  type === 'batch'
                    ? `总共成功注销
                      ${res.successNum}个，还有
                       ${res.total - res.successNum}
                      个未成功`
                    : res.fail[0].split(':')[1] || '注销失败',
                type: 'error',
              })
            }
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },
    refreshTable() {
      this.$refs['tableSearch'].refreshTable()
    },
    handleAdd() {
      this.addDeviceVisible = true
      this.stationAttr = {
        ...this.$attrs.stationAttr,
        type: this.$attrs.type,
      }
    },
    handleBatchUpload(type) {
      this.batchUploadVisible = true
      this.dialogType = type
      this.stationAttr = {
        ...this.$attrs.stationAttr,
        type: this.$attrs.type,
      }
    },
    async handleExport(row) {
      let data = []
      if (!this.tableData || !this.tableData.totalCount) {
        this.$message({
          message: '没有设备二维码可以导出',
          type: 'warning',
        })
        return
      }
      if (row) {
        // if (row.socketId) {
        //   data.push({ socketId: row.socketId })
        // } else {
        //   data.push({ socketId: row.deviceId })
        // }
        data.push({ socketId: row.deviceId })
      } else {
        let params = {
          currentPage: 1,
          pageSize: this.tableData.totalCount,
          deviceType: this.$attrs.type,
          stationId: this.$route.params.id,
        }
        let station = await stationDetailList(params)
        station.list.forEach((item) => data.push({ socketId: item.deviceId }))
      }

      genQrcode(data)
    },
    handleMigrate(row) {
      this.deviceAttr = row
      this.migrateDeviceVisible = true
    },
    handleSelfCheck(row) {
      const loading = this.$loading({
        lock: true,
        text: '设备自检中……',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })

      var socketId = row.type == 'CENTRAL_SOCKET' ? row.deviceId : row.socketId

      detailSelfCheck({ socketId: socketId }).then(
        (res) => {
          loading.close()
          this.$message({
            message: res.breakDownReason || '自检成功',
            type: 'success',
            showClose: true,
          })
          this.refreshTable()
        },
        () => {
          loading.close()
        }
      )
    },
    handleCoupletCardStatus(row) {
      coupletCardStatus({ deviceId: row.deviceId }).then((res) => {
        this.coupletCard = res
        this.coupletCardVisible = true
      })
    },
    handleLabel(row) {
      this.editLabelVisible = true
      this.deviceAttr = row
    },
    handleGetPartner() {
      return false
      partnerList().then((res) => {
        console.log(res)
        this.partnerOptions = res.map((_) => {
          return {
            value: _.id,
            label: _.partnerName,
          }
        })
      })
    },
  },
}
</script>
